import pathToRegexp from 'path-to-regexp';
import {isUrl} from '@/utils/numberUtils';
import {Icon} from 'antd';
import IconFont from '@/components/IconFont';
import {urlToList} from '@/utils/pathUtils';

export const getIcon = icon => {
    if (typeof icon === 'string') {
        if (isUrl(icon)) {
            return <Icon component={() => <img src={icon} alt="icon"/>}/>;
        }
        if (icon.startsWith('icon-')) {
            return <IconFont type={icon}/>;
        }
        return <Icon type={icon}/>;
    }
    return icon;
};

export const getMenuMatches = (flatMenuKeys=[], path) =>
    flatMenuKeys.filter(item => {
        if (item) {
            return pathToRegexp(item).test(path);
        }
        return false;
    });

//获得菜单子节点
export const getDefaultCollapsedSubMenus = props => {
    const {
        location: {pathname},
        flatMenuKeys,
    } = props;
    return urlToList(pathname)
        .map(item => getMenuMatches(flatMenuKeys, item)[0])
        .filter(item => item)
        .reduce((acc, curr) => [...acc, curr], ['/']);
};
